package com.example.controller;

import com.alibaba.fastjson.JSON;
import com.example.common.jwt.JwtTokenUtils;
import com.example.common.utils.R;
import com.example.entity.ImGroup;
import com.example.entity.ImSingle;
import com.example.entity.User;
import com.example.service.ImGroupService;
import com.example.service.ImSingleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 描述：群组聊天相关接口
 */
@RestController
@RequestMapping(value = "/imGroup")
@Api(tags = "群组聊天管理")
public class ImGroupController {

    @Autowired
    private ImGroupService imGroupService;

    @Autowired
    private ImSingleService imSingleService;

    /**
     * 描述：新增群组
     */

    /**
     * 描述：根据ID删除群组
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除群组", notes = "根据群组ID删除群组")
    public R delete(@PathVariable Integer id) {
        imGroupService.delete(id);
        return R.success();
    }

    @PostMapping
    @ApiOperation(value = "新增群组", notes = "创建一个新的群组")
    public R add(@RequestBody Map<String, Object> requestBody) {
        // 获取用户列表
        List<Map<String, Object>> usersData = (List<Map<String, Object>>) requestBody.get("user");
        List<User> users = new ArrayList<>();

        // 将 Map 转换为 User 对象列表
        for (Map<String, Object> userData : usersData) {
            User user = new User();
            user.setId((Integer) userData.get("id"));
            user.setName((String) userData.get("name"));
            users.add(user);
        }

        // 获取群组名称
        String groupName = (String) requestBody.get("GroupName");

        // 构建群组对象
        ImGroup imGroup = new ImGroup();
        List<String> groupNameList = new ArrayList<>();

        // 将用户ID加入群组
        for (User user : users) {
            groupNameList.add(user.getId().toString());
        }

        // 获取当前用户并将其ID也加入到群组内容中
        User currentUser = JwtTokenUtils.getCurrentUser();  // 获取当前用户
        if (currentUser != null) {
            groupNameList.add(currentUser.getId().toString());  // 将当前用户的ID加入到群组内容中
        }
        //设置群组内容和其它属性
        imGroup.setContent(groupNameList.toString());
        imGroup.setName(groupName);
        // 格式化当前时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = dateFormat.format(new Date());
        imGroup.setTime(currentTime);
        //设置默认的群组类型和头像
        imGroup.setType("0"); // 群组类型
        imGroup.setAvatar("http://47.100.198.147:7791/im-system/48033bae10e7fb7632705339aa3a499b.jpeg"); // 默认头像
        // 调用服务层进行群组添加
        imGroupService.add(imGroup);
        // 返回成功响应
        return R.success();
    }


    /**
     * 描述：更新群组信息
     */
    @PutMapping
    @ApiOperation(value = "更新群组", notes = "更新指定群组的信息")
    public R update(@RequestBody ImGroup imGroup) {
        imGroupService.update(imGroup);
        return R.success();
    }

    /**
     * 描述：根据ID查询群组
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "查询群组", notes = "根据群组ID查询群组详细信息")
    public R detail(@PathVariable Integer id) {
        ImGroup imGroup = imGroupService.findById(id);
        return R.success(imGroup);
    }

    /**
     * 描述：查询所有群组
     */
    @GetMapping
    @ApiOperation(value = "查询所有群组", notes = "获取当前用户参与的所有群组")
    public R all() {
        // 获取当前用户
        User currentUser = JwtTokenUtils.getCurrentUser();
        Integer currentUserId = currentUser.getId();

        // 获取所有群组信息
        List<ImGroup> allGroups = imGroupService.findAll();

        // 获取当前用户参与的群组
        List<ImGroup> userGroups = allGroups.stream()
                .filter(group -> {
                    String content = group.getContent();
                    if (content != null && !content.isEmpty()) {
                        content = content.replaceAll("[\\[\\] ]", ""); // 去掉方括号和空格
                        List<Integer> context = Arrays.stream(content.split(","))
                                .map(str -> Integer.parseInt(str.trim()))  // 去掉每个字符串中的空格
                                .collect(Collectors.toList());
                        return context.contains(currentUserId); // 判断当前用户ID是否在群组成员中
                    }
                    return false;
                })
                .collect(Collectors.toList());
        // 返回当前用户参与的群组
        return R.success(userGroups);
    }





    /**
     * 描述：分页查询群组
     */
    @PostMapping("/page")
    @ApiOperation(value = "分页查询群组", notes = "根据条件分页查询群组")
    public R page(@RequestBody ImGroup search,
                  @RequestParam(defaultValue = "1") Integer pageNum,
                  @RequestParam(defaultValue = "5") Integer pageSize) {
        return R.success(imGroupService.findPage(search, pageNum, pageSize));
    }

    /**
     * 查询所有消息
     */
    @GetMapping("/all/{groupId}")
    @ApiOperation(value = "查询群聊聊天消息", notes = "根据群组id查询聊天记录")
    public R findByFromUsername(@PathVariable Integer groupId) {
        List<ImSingle> all = imSingleService.findByGroupId(groupId);
        return R.success(all);
    }

    /**
     * 群聊
     */
}
